import { createRouter, createWebHistory, type RouteLocationNormalized, type RouteMeta, type RouteRecordRaw } from 'vue-router'

// 路由声明文件，扩展基础路由对象属性( 为 addRoute 参数扩展meta)
declare module 'vue-router' {
    interface _RouteRecordBase {
        meta?: RouteMeta
    }
}

// 预跳转地址 (用于动态处理跳转)
let $preRouteInfo: RouteLocationNormalized = {
    matched: [],
    fullPath: '',
    hash: '',
    query: {},
    params: {},
    name: undefined,
    meta: {},
    path: '',
    redirectedFrom: undefined,
};

// 当前路由信息
let $nowRouteInfo: RouteLocationNormalized = $preRouteInfo;

// 上次路由信息
let $beforeRouteInfo: RouteLocationNormalized = $preRouteInfo;

// 页面资源字典
const pageSourceMap = import.meta.glob('@page/*/*.vue');

// 创建路由
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        // 自动路由生成
        ...Object.keys(pageSourceMap).map((sourcePath: string): RouteRecordRaw => {
            return {
                path: sourcePath.match(/^\/src\/page([\W\w]+)\.vue$/)![1],
                component: () => {
                    return pageSourceMap[sourcePath]()
                }
            }
        }),
        {
            path: '/',
            component: () => {
                return import('@page/master/index.vue')
            },
        },
        {
            path: '/404',
            meta: { test: true },
            component: () => {
                return import('@page/comm/404.vue')
            },
        },
        {
            path: '/:default',
            meta: { keepAlive: false },
            component: () => import('@page/comm/404.vue')
        },
    ],
})


export default router;


// 全局路由守卫
router.beforeEach((to, _from) => {
    // 即将访问的路由信息
    $preRouteInfo = to;
    // 检查页面资源是否能匹配，否则跳转404页面(兜底处理)
    if (to.matched.length === 0) {
        return '/404'
    }
    return true;
})

// 全局解析守卫,获取数据或执行任何其他操作（如果用户无法进入页面时你希望避免执行的操作）的理想位置。
router.beforeResolve((to, _from) => {
    if (to.meta.requiresCamera) {

    }
})

// 全局后置钩子
// router.afterEach((to, from) => {

// // })


/**
 * 动态添加路由
 * @param title
 * @param path
 * @param componentPath
 */
export function addRouter({ title, path, componentPath, meta }: { title: string, path: string, componentPath: string, meta: RouteMeta }) {
    router.addRoute({
        path,
        meta: Object.assign({ title }, meta),
        component: () => {
            return pageSourceMap['/src/page' + componentPath + '.vue']()
        }
    })
}
